package ace.game.level;

import javax.microedition.lcdui.Graphics;
import ace.game.Tileset;

import ace.system.Utilities;
import ace.system.xml.XmlNode;
import ace.system.xml.XmlReaderWriter;

public class Map {
	protected Map() {
		//initialize
		m_Width		= 1;
		m_Height	= 1;
		m_Tiles		= null;
		m_Tileset	= null;
	}

	public Map(String mapStr, String tileset) {
		//Default
		this();

        String tilesetImg = null;
        XmlNode xmlNode = XmlReaderWriter.getInstance().readFromXmlFile(Utilities.TILESET_FOLDER + "/" + tileset);

		//For each children
        for(int i=0; i<xmlNode.getChildren().size(); ++i){
			//Read tag
            String Tag 		= ((XmlNode)xmlNode.getChildren().elementAt(i)).getNodeName();
			String Value 	= ((XmlNode)((XmlNode)xmlNode.getChildren().elementAt(i)).getChildren().elementAt(0)).getNodeValue();

			//Save based on tag
            if(Tag.equals("image"))	tilesetImg = Value;
        }


		//Create tileset
		m_Tileset = new Tileset(Utilities.TILESET_FOLDER + "/" + tilesetImg);

		//Get height
		if (System.getProperty("line.separator") != null)	m_Height = Utilities.split(mapStr, System.getProperty("line.separator")).length;
		else												m_Height = Utilities.split(mapStr, 10).length;

		//Get tiles
		String[] splitted	= Utilities.split(mapStr, ";");
		m_Width				= splitted.length / m_Height;
		m_Tiles				= new int[m_Width][m_Height];
		
		//Fill the m_Tiles
		for(int i=0; i<m_Height; ++i) {
			for(int j=0; j<m_Width; ++j) {
				m_Tiles[j][i] = Integer.parseInt(splitted[(i*m_Width) + j]);
			}
		}
	}

	public int getWidth() {
		return m_Width;
	}

	public int getHeight() {
		return m_Height;
	}

	public void draw(Graphics g, int startX, int startY, int endX, int endY) {
		int fromTileX = startX / Utilities.TILE_WIDTH;
		int fromTileY = startY / Utilities.TILE_HEIGHT;
		int endTileX = endX / Utilities.TILE_WIDTH + 1;
		int endTileY = endY / Utilities.TILE_HEIGHT + 1;
		int offsetX = startX - fromTileX * Utilities.TILE_WIDTH;
		int offsetY = startY - fromTileY * Utilities.TILE_HEIGHT;

		if (fromTileX < 0)			fromTileX	= 0;
		if (endTileX >= m_Width)	endTileX	= m_Width - 1;
		if (fromTileY < 0)			fromTileY	= 0;
		if (endTileY >= m_Height)	endTileY	= m_Height - 1;

		//Draw tiles
		for (int y = endTileY - 1; y >= fromTileY; y--) {
			for (int x = fromTileX; x < endTileX; x++) {
				//Draw
				g.drawImage(
					m_Tileset.getTile(m_Tiles[x][y]),
					((x - fromTileX) * Utilities.TILE_WIDTH - offsetX),
					((y - fromTileY) * Utilities.TILE_HEIGHT - offsetY),
					Graphics.LEFT | Graphics.TOP );
			}
		}
	}
	
	//Data
	protected int 		m_Width;
	protected int 		m_Height;
	protected int[][] 	m_Tiles;
	protected Tileset	m_Tileset;
}

